<?php
require_once(dirname(__FILE__) . '/AnotaAutoloader.class.php');

/**
 * This file is part of the Anota project.
 * 2011-2012 Fernando Garcia Huerta <fgarciahue@uoc.edu>
 * 
 * UOC - FUNDAMENTOS DE INFORMÁTICA EN ENTORNOS BIOINFORMÁTICOS - PEC2
 */

/**
 * Application Controller.
 *
 * - loads and executed the solicited module/action
 * 
 * @package    Anota
 * @subpackage application
 * @author     Fernando Garcia Huerta <fgarciahue@uoc.edu>
 */
class AnotaController {
    public static 
        $content;   // final content to be displayed
    
    /**
     * Analizes request and actuates in consequence.
     * 
     * @param AnotaConfig $config Configuration of the application
     */
    public static function dispatch(AnotaConfig $config) {
        
        // obtain requested module (default: About)
        // and builds template name
        $module_name = 'About';
        if (isset($_POST['module']))
            $module_name = $_POST['module'];
        if (isset($_GET['module']))
            $module_name = $_GET['module'];        
        $template_name = 'template' . $module_name . '.php';

        // obtain requested action (default: Index)
        $action = 'executeIndex';
        if (isset($_POST['action']))
            $action = 'execute' . $_POST['action'];
        if (isset($_GET['action']))
            $action = 'execute' . $_GET['action'];

        // builds requested module class and executes the action
        $class = 'AnotaModule' . $module_name;
        $module = new $class($config);
        $module->setTemplate($template_name);
        $module->$action();
        
        // renders result
        self::render($config, $module);
    }

    /**
     * Echoes content
     * 
     * @param AnotaConfit $config 
     * @param AnotaMOduleBase $module 
     */
    protected static function render($config, $module)
    {
        self::$content = $module->render();
        
        if (null !== $config->getGlobalTemplate()) {            
            include ($config->getGlobalTemplate());
        }        
    }
}